{extend name="index_layout"/}
{block name="main"}
<div class="layui-card">
    <div class="layui-card-header">菜单管理</div>
    <div class="layui-card-body">
        <div class="layui-form">
            <table class="layui-hide" id="treeTable" lay-filter="treeTable"></table>
        </div>
    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <a class="layui-btn layui-btn-sm" href="{:url('form')}">新增后台菜单</a>
        <a class="layui-btn layui-btn-sm layui-btn-normal" id="openAll">展开或折叠全部</a>
        <a class="layui-btn layui-btn-sm layui-btn-danger" id="delAll">批量删除</a>
    </div>
</script>
<script type="text/html" id="barTool">
    <a href='{:url("form")}?id={{ d.id }}' class="layui-btn layui-btn-xs">编辑</a>
    <a href='{:url("form")}?parentid={{ d.id }}' class="layui-btn layui-btn-xs layui-btn-normal">添加</a>
    <a href='{:url("delete")}?id={{ d.id }}' class="layui-btn layui-btn-danger layui-btn-xs menu-del">删除</a>
</script>
<script type="text/html" id="switchTpl">
    <input type="checkbox" name="status" data-href="{:url('Common/setState')}?id={{d.id}}&model=menu&field=status"
           value="{{d.id}}" lay-skin="switch" lay-text="显示|隐藏" lay-filter="switchStatus" {{ d.status==1
           ? 'checked' : '' }}>
</script>

{/block}
{block name="script"}
<script>
    var treeGrid = null;
    layui.use(['table', 'treeGrid'], function () {
        var $ = layui.$,
            treeGrid = layui.treeGrid,
            tableId = 'treeTable',
            ptable = null;
        ptable = treeGrid.render({
            id: tableId,
            elem: '#' + tableId,
            toolbar: '#toolbarDemo',
            idField: 'id',
            url: "{:url('index')}",
            cellMinWidth: 100,
            treeId: 'id', //树形id字段名称
            treeUpId: 'parentid', //树形父id字段名称
            treeShowName: 'title', //以树形式显示的字段
            height: 'full-140',
            isFilter: false,
            iconOpen: false, //是否显示图标【默认显示】
            isOpenDefault: false, //节点默认是展开还是折叠【默认展开】
            onDblClickRow: false, //去除双击事件
            cols: [
                [
                    {type: 'checkbox'},
                    {field: 'id', align: 'center', width: 60, title: 'ID'},
                    {field: 'title', title: '菜单名称', width: 350},
                    {
                        width: 80,
                        title: '图标',
                        align: 'center',
                        templet: "<div><i class='iconfont {{d.icon}}'></i></div>"
                    },
                    {
                        width: 350,
                        title: '模块/控制器/方法',
                        templet: "<div>{{d.app}}{{# if (d.controller) { }}/{{d.controller}}{{# } }}{{# if (d.action) { }}/{{d.action}}{{# } }}</div>"
                    },
                    {
                        field: 'status',
                        align: 'center',
                        width: 120,
                        title: '状态',
                        templet: '#switchTpl',
                        unresize: true
                    },
                    {field: 'listorder', align: 'center', width: 60, title: '排序', edit: 'text'},
                    {fixed: 'right', align: 'center', width: 200, title: '操作', toolbar: '#barTool'}
                ]
            ],
            page: false,
            // 使用 done 事件在数据渲染完成后展开一二级菜单
            done: function(res, curr, count){
                var data = res.data;
                // 遍历数据，找出一二级菜单并展开
                data.forEach(function(item) {
                    if (item.parentid === 0) { // 一级菜单
                        treeGrid.treeNodeOpen(tableId, item, true);
                        // // 查找二级菜单并展开
                        // data.forEach(function(subItem) {
                        //     if (subItem.parentid === item.id) {
                        //         // treeGrid.treeOpen(tableId, subItem.id);
                        //         treeGrid.treeNodeOpen(tableId, subItem, true);
                        //     }
                        // });
                    }
                });
            }
        })

        // 定义一个变量来存储展开状态
        var expandedNodes = [];
        // 在需要的地方（例如初始化时或展开/折叠节点时）记录状态
        treeGrid.on('node(fold)', function(obj){
            var id = obj.data.id;
            if(expandedNodes.includes(id)){
                expandedNodes = expandedNodes.filter(item => item !== id);
            }
            console.log(expandedNodes)
        });

        treeGrid.on('node(unfold)', function(obj){
            var id = obj.data.id;
            if(!expandedNodes.includes(id)){
                expandedNodes.push(id);
            }
            console.log(expandedNodes)
        });

        //监听单元格编辑
        treeGrid.on('edit(treeTable)', function (obj) {
            var value = obj.value,
                data = obj.data;
            $.post('{:url("listorder")}', {'id': data.id, 'value': value}, function (data) {
                if (data.code == 1) {
                    layer.msg(data.msg, {time: 1000, icon: 1}, function () {
                        // treeGrid.reload(tableId)
                    });
                } else {
                    layer.msg(data.msg);
                }

            })
        });

        $(document).on('click', '#openAll', function () {
            var treedata = treeGrid.getDataTreeList(tableId);
            treeGrid.treeOpenAll(tableId, !treedata[0][treeGrid.config.cols.isOpen]);
        })

        $(document).on('click', '#delAll', function () {
            layer.confirm('{:lang("是否删除选中数据？")}', {icon: 3}, function (index) {
                layer.close(index);
                var checkStatus = treeGrid.checkStatus(tableId)
                    , data = checkStatus.data;
                var ids = [];
                $(data).each(function (i, o) {
                    ids.push(o.id);
                });
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.post("{:url('delall')}", {ids: ids}, function (data) {
                    layer.close(loading);
                    if (data.code === 0) {
                        layer.msg(data.msg, {time: 1000, icon: 1}, function () {
                            treeGrid.reload(tableId)
                        });
                    } else {
                        layer.msg(data.msg, {time: 1000, icon: 2});
                    }
                });
            });
        })

        $(document).on('click', '.menu-del', function () {
            var that = $(this),
                href = !that.attr('data-href') ? that.attr('href') : that.attr('data-href');
            layer.confirm('删除之后无法恢复，您确定要删除吗？', {icon: 3, title: '提示信息'}, function (index) {
                if (!href) {
                    notice.info('请设置data-href参数');
                    return false;
                }
                $.get(href, function (data) {
                    if (data.code == -1) {
                        layer.msg(data.msg, {time: 1000, icon: 2});
                    } else {
                        layer.msg(data.msg, {time: 1000, icon: 1}, function () {
                            treeGrid.reload(tableId)
                        });
                    }
                });
                layer.close(index);
            });
            return false;
        });
    });
</script>
{/block}
